<?php

namespace app\admin\controller;

use app\common\model\AdminUser;
use app\common\controller\Base;
use app\common\service\AdminToken;
use app\Request;
use think\App;
use think\exception\ValidateException;
use think\facade\Cookie;
use think\facade\Validate;
use think\facade\View;

/**
 * 公共页面
 * Class Common
 * @package app\admin\controller
 */
class Common extends Base
{

    public function __construct(App $app)
    {
        parent::__construct($app);
        //使用thinkphp的验证器
        $this->validate = Validate::rule(['username' => 'require|alphaDash|length:6,30', 'password' => 'require|length:6,30']);
    }

    /**
     * 管理员登录
     * @param Request $request
     * @return string|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(Request $request)
    {
        if ($request->isPost()) {
            try {
                validate(\app\validate\AdminUser::class)->scene('login')->check($request->post());

                $adminUser = new AdminUser();
                $rs = $adminUser->login($request->post('username'), $request->post('password'));
                if (isset($rs) && $rs['id']) {
                    $admintoken = new AdminToken();
                    $tokenArr = $admintoken->setToken(intval($rs['id']), ['username' => $rs['username'], 'tenant_id' => $rs['tenant_id']]);
                    //登录成功写cookie
                    Cookie::set('admin_token', $tokenArr['admin_token']);
                    Cookie::set('admin_username', $tokenArr['username']);

                    return $this->success('登录成功', '/admin/');
                } else {
                    return $this->error('账号密码错误');
                }
            } catch (ValidateException $e) {
                return $this->error($e->getMessage());
            }
        } else {
            return View::fetch();
        }
    }

    public function register()
    {
        return View::fetch();
    }

    public function logout()
    {
        Cookie::delete('admin_token');
        Cookie::delete('admin_username');

        return redirect('/admin/login');
    }
}
